import authorizeApi from '@/api/AuthorizeApi'
export default {
  namespaced: true,
  state: {
    ACCESS_TOKEN: '', // 访问
    USER_INFO: {userName: '--', roleName: '', mobile: '', email: '', status: ''}, // 用户信息
    PERMISSIONS: []  // 权限信息
  },
  getters: {
    // 是否登录
    isAuthorize(state) {
      return !(state.ACCESS_TOKEN=='')
    },
    // 权限
    permissions(state){      
      return state.PERMISSIONS
    }
  },
  mutations: {
    setAccessToken(state, payloay) {
      state.ACCESS_TOKEN = payloay
    },
    setUserInfo(state, payload) {
      state.USER_INFO = payload
    },
    setPermissions(state, payload){
      state.PERMISSIONS = payload
    },
    // 重置状态
    resetState(state) {
      state.ACCESS_TOKEN = ''
      state.USER_INFO = {userName: '--', roleName: '', mobile: '', email: '', status: ''}, // 用户信息
      state.PERMISSIONS = []  // 权限信息
    }
  },
  actions: {
    // 登录系统
    login(context, payload) {
      return authorizeApi.doLogin(payload).then(res => {
        if (res.code == 0) {
          // 调用菜单模块中[menu.js]加载菜单
          context.dispatch('menu/initNavMenuData', {}, { root: true })
          // 保存数据
          context.commit('setAccessToken', res.data.accessToken)
          context.commit('setUserInfo', res.data.userInfo)
          return Promise.resolve('登录成功')
        } else {
          return Promise.reject(res.msg)
        }
      }).catch(err => {
        return Promise.reject(err)
      })
    },
    // 退出系统
    logout(context) {
      // console.dir()
      return authorizeApi.doLogout().then(res => {

        if (res.code == 0) {
          context.commit('resetState')
          // 在模块调用state根的mutations里面的方法
          context.commit('menu/resetState', null, { root: true })
          return Promise.resolve(res.msg)
        } else {
          return Promise.reject(res.msg)
        }
      }).catch(err => {
        return Promise.reject(err)
      })
    },
    // 设置菜单权限
    setPermis(context, payload){
      context.commit('setPermissions', payload)
    }
  }
}
